package com.example.springboot.services.impl;

import com.example.springboot.domain.Menu;
import com.example.springboot.mapper.MenuMapper;
import com.example.springboot.services.MenuService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Override
    public List<Menu> getAllMenus() {

        List<Menu> allMenus ;
        allMenus = menuMapper.selectList(null);
        List<Menu> menuList = new ArrayList<>();

        /**
         * 找到根菜单
         */
        for (int index = 0; index < allMenus.size();) {
            if( 0 == (allMenus.get(index).getParentId()) ){
                menuList.add(allMenus.get(index));
                allMenus.remove(index);
            }else { index++ ;}
        }

        for (Menu menu : menuList) {
            menu.setChildMenus(getChild(menu.getId(), allMenus));
        }

        return menuList;

    }

    @Override
    public List<Menu> getRoleMenus(Integer roleId) {


        List<Menu> allMenus ;
        allMenus = menuMapper.getRoleMenu(roleId);
        List<Menu> menuList = new ArrayList<>();

        /**
         * 找到根菜单
         */
        for (int index = 0; index < allMenus.size();) {
            if( 0 == (allMenus.get(index).getParentId()) ){
                menuList.add(allMenus.get(index));
                allMenus.remove(index);
            }else { index++ ;}
        }

        for (Menu menu : menuList) {
            menu.setChildMenus(getChild(menu.getId(), allMenus));
        }

        return menuList;

    }


    List<Menu> getChild(Integer id, List<Menu> allMenus){
        //检查是否还存在子菜单
        List<Menu> childList = new ArrayList<>();
        for (int index = 0; index < allMenus.size(); ) {
            if(id == (allMenus.get(index).getParentId())){
                childList.add(allMenus.get(index));
                allMenus.remove(allMenus.get(index));
            }else { index++; }
        }
        //没有子节点返回全部子节点
        if( childList.size() == 0){
            return null;
        }
        //有子节点，对子节点递归
        for (Menu menu : childList) {
            menu.setChildMenus(getChild(menu.getId(),allMenus));
        }
        return childList;
    }


}
